package istar.impl;

import istar.IActor;
import istar.IResource;
import istar.agent.IstarJadeAgent;
import jade.content.Concept;

import java.util.Iterator;

public class Resource extends AbstractElement implements IResource, Concept{

	private double value=0;
	private int quantity=1;
	private boolean avaliable=false;

	public Resource(String _name){
		super(_name);
	}
	
	public Resource(String _name, IActor owner){
		super(_name, owner);
	}

	@Override
	public int getQuantity() {
		return quantity;
	}

	@Override
	public void setQuantity(int value) {
		this.quantity = value;
	}

	@Override
	public double getValue() {
		return value;
	}

	@Override
	public void setValue(double value) {
		this.value = value;
	}

	public boolean getAvaliable(IstarJadeAgent _agent) {
		Iterator<IResource> itResources = _agent.getResources().iterator();
		while (itResources.hasNext()){
			IResource resource = itResources.next();
			if (resource.getName().equals(this.getName())){
				return true;
			}
		}
		return false;
	}
	
	


	public boolean obtain(IstarJadeAgent _agent, int quantity) {
		Iterator<IResource> itResources = _agent.getResources().iterator();
		while (itResources.hasNext()){
			IResource resource = itResources.next();
			if (resource.getName().equals(this.getName())){
				int initialQtt = resource.getQuantity();
				resource.setQuantity(initialQtt-quantity);
				return true;
			}
		}
		return false;		
		/*
		if (this.getIsBasic()){
			Iterator<IResource> itResources = _agent.getResources().iterator();
			while (itResources.hasNext()){
				IResource resource = itResources.next();
				if (resource.getName().equals(this.getName())){
					int initialQtt = resource.getQuantity();
					resource.setQuantity(initialQtt-quantity);
					return true;
				}
			}
		}
		else {
			MeansSimpleBehaviour behaviour = new MeansSimpleBehaviour(this);
			_agent.addBehaviour(behaviour);
		}
		return false;		
		*/
	}
	
	public int obtainAll(IstarJadeAgent _agent) {
		int qtt = 0; 
		Iterator<IResource> itResources = _agent.getResources().iterator();
		while (itResources.hasNext()){
			IResource resource = itResources.next();
			if (resource.getName().equals(this.getName())){
				qtt = resource.getQuantity();
				if (this.isBasic()){
					resource.setQuantity(0);
				} 
				else {
					if (obtain(_agent, qtt))
						return qtt;
					else 
						return 0;
				}
			}
		}
		return qtt;
	}

	@Override
	public boolean achieved() {
		// TODO Auto-generated method stub
		return (this.avaliable);
	}

	

}
